package com.onlineOrder.webAction;

import com.onlineOrder.bean.indentList;
import com.onlineOrder.bean.menuList;
import com.onlineOrder.bean.userList;
//import com.onlineOrder.time.timeCounter;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@WebServlet({"/userDetail","/userOrder","/userModify","/userMenuSearch","/userMenuReport","/userMenuBuy","/userBuyList","/indentStateUpdate"})
public class userServlet extends HttpServlet {

    public static boolean resultAlert=false;
    public static String userAddress="";

    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String servletPath = request.getServletPath();
        if (servletPath.equals("/userDetail")){
            doUserDetail(request,response);
        }else if (servletPath.equals("/userOrder")){
            doUserOrder(request,response);
        }else if (servletPath.equals("/userModify")){
            doUserModify(request,response);
        }else if (servletPath.equals("/userMenuSearch")){
            doUserMenuSearch(request,response);
        }else if (servletPath.equals("/userMenuReport")){
            doUserMenuReport(request,response);
        }else if (servletPath.equals("/userMenuBuy")){
            doUserMenuBuy(request,response);
        }else if (servletPath.equals("/userBuyList")){
            doUserBuyList(request,response);
        }else if (servletPath.equals("/indentStateUpdate")){
            doIndentStateUpdate(request,response);
        }
    }

    private void doIndentStateUpdate(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String indentID = request.getParameter("indentID");
        String indentTime = request.getParameter("indentTime");

        Connection conn=null;
        PreparedStatement ps=null;
        ResultSet rs=null;

        int count=0;
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            conn=DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/onlineOrder","root","123456");
            String sql="update indent set state='1' where num=?";
            ps=conn.prepareStatement(sql);
            ps.setString(1,indentID);

            count=ps.executeUpdate();
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (count==1){
            request.getRequestDispatcher("/userBuyList").forward(request,response);
        }else {
            request.getRequestDispatcher("error.jsp").forward(request,response);
        }

    }

    private void doUserBuyList(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String userID=loginServlet.ID;

        Connection conn=null;
        PreparedStatement ps=null;
        ResultSet rs=null;

        List<indentList> buyLists = new ArrayList<>();
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            conn=DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/onlineOrder","root","123456");
            String sql="select menus,amount,shopName,phone,time,address,state,num from indent where userId=?";
            ps=conn.prepareStatement(sql);
            ps.setString(1,userID);

            rs=ps.executeQuery();
            while (rs.next()){
                indentList indentList = new indentList();

                indentList.setMenus(rs.getString("menus"));
                indentList.setAmount(rs.getString("amount"));
                indentList.setShopName(rs.getString("shopName"));
                indentList.setPhone(rs.getString("phone"));
                indentList.setTime(rs.getString("time"));
                indentList.setAddress(rs.getString("address"));
                indentList.setState(rs.getString("state"));
                indentList.setNum(rs.getString("num"));

                buyLists.add(indentList);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        // 将一个集合放到请求域当中
        request.setAttribute("buyLists",buyLists);

        // 转发（不要重定向）
        request.getRequestDispatcher("/userMenuBuy.jsp").forward(request, response);
    }

    private void doUserMenuBuy(HttpServletRequest request, HttpServletResponse response) throws IOException {

        String userID=loginServlet.ID;
        int menuNum= Integer.parseInt(request.getParameter("menuNum"));
        String menuName = request.getParameter("menuName");
        String  Price= request.getParameter("menuPrice");
        int menuPrice= Integer.parseInt(Price.substring(0,Price.length()-2));
        String shopName=request.getParameter("shopName");
        String shopPhone=request.getParameter("shopPhone");
        String shopID=request.getParameter("shopID");

        String all= String.valueOf(menuNum*menuPrice);
        String address=userAddress;

        SimpleDateFormat dateTime = new SimpleDateFormat("MM-dd HH:mm:ss");

        Connection conn=null;
        PreparedStatement ps=null;
        ResultSet rs=null;

        int count=0;

        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            conn=DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/onlineOrder","root","123456");
            String sql="insert into indent(`menus`,`amount`,`state`,`phone`,`shopName`,`userName`,`userId`,`time`,`shopId`,`address`) values(?,?,?,?,?,?,?,?,?,?)";
            ps= conn.prepareStatement(sql);
            ps.setString(1,menuName);
            ps.setString(2,all);
            ps.setString(3,"0");
            ps.setString(4,shopPhone);
            ps.setString(5,shopName);
            ps.setString(6,loginServlet.homeName);
            ps.setString(7,userID);
            ps.setString(8,dateTime.format(new Date()));
            ps.setString(9,shopID);
            ps.setString(10,address);

            count=ps.executeUpdate();
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (count==1){
            response.sendRedirect(request.getContextPath()+"/userOrder");
        }else{
            response.sendRedirect(request.getContextPath()+"/error.jsp");
        }


    }

    private void doUserMenuReport(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String shopID = request.getParameter("shopID");

        Connection conn=null;
        PreparedStatement ps=null;
        ResultSet rs=null;

        int count=0;

        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            conn=DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/onlineOrder","root","123456");
            String sql="update shop set state='有投诉' where id=?";
            ps=conn.prepareStatement(sql);
            ps.setString(1,shopID);

            count=ps.executeUpdate();

        } catch (Exception e) {
            e.printStackTrace();
        }
        if (count==1){
            response.sendRedirect(request.getContextPath()+"/userMenuList.jsp");
        }else{
            response.sendRedirect(request.getContextPath()+"/error.jsp");
        }
    }

    private void doUserMenuSearch(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        String search=request.getParameter("searchResult");
//        search="宫廷玉液酒";

        Connection conn=null;
        PreparedStatement ps=null;
        ResultSet rs=null;

        List<menuList> menuLists = new ArrayList<>();
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            conn=DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/onlineOrder","root","123456");
            String sql="select * from menu where menus=?||shopName=?||shopPhone=?";
            ps=conn.prepareStatement(sql);
            ps.setString(1,search);
            ps.setString(2,search);
            ps.setString(3,search);

            rs=ps.executeQuery();
            while (rs.next()){
                menuList menuList = new menuList();

                menuList.setIdPic(rs.getString("idpic"));
                menuList.setMenus(rs.getString("menus"));
                menuList.setImg(rs.getString("img"));
                menuList.setPrice(rs.getString("price"));
                menuList.setShopName(rs.getString("shopName"));
                menuList.setShopID(rs.getString("shopID"));
                menuList.setShopPhone(rs.getString("shopPhone"));

                menuLists.add(menuList);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        // 将一个集合放到请求域当中
        request.setAttribute("menuList",menuLists);

        // 转发（不要重定向）
        request.getRequestDispatcher("/userMenuList.jsp").forward(request, response);
    }

    private void doUserModify(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String userId=request.getParameter("userID");
        String newUserName=request.getParameter("newUserName");
        String newUserPwd=request.getParameter("newUserPwd");
        String newUserPhone=request.getParameter("newUserPhone");
        String newUserAddress=request.getParameter("newUserAddress");

        String contextPath = request.getContextPath();
        int count=0;

        Connection conn=null;
        PreparedStatement ps=null;
        ResultSet rs=null;

        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            conn=DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/onlineOrder","root","123456");
            String sql="update user set userName=?,Pwd=?,phone=?,address=? where id=?";
            ps=conn.prepareStatement(sql);
            ps.setString(1,newUserName);
            ps.setString(2,newUserPwd);
            ps.setString(3,newUserPhone);
            ps.setString(4,newUserAddress);
            ps.setString(5,userId);

            count= ps.executeUpdate();
            if (count!=0){
                resultAlert=true;
                response.sendRedirect(contextPath+"/userDetail");
            }else{
                response.sendRedirect(contextPath+"/error.jsp");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }



    }

    private void doUserOrder(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Connection conn=null,conn2=null;
        PreparedStatement ps=null,ps2=null;
        ResultSet rs=null,rs2=null;

        List<menuList> menuLists = new ArrayList<>();
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            conn=DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/onlineOrder","root","123456");
            String sql="select * from menu";
//            String sql2="select count(*) from menu";

            ps=conn.prepareStatement(sql);
//            ps2=conn2.prepareStatement(sql2);

//            rs2=ps2.executeQuery();
//            if (rs2.next()){
//                totalRecords=rs2.getInt(1);//总数据数
//            }
//            if (totalRecords%3==0)
//                totalPages=totalRecords/3;
//            else
//                totalRecords=totalPages/3+1;
//
//            currentPage=1;

            rs=ps.executeQuery();
            while (rs.next()){
                menuList menuList = new menuList();

                menuList.setIdPic(rs.getString("idpic"));
                menuList.setMenus(rs.getString("menus"));
                menuList.setImg(rs.getString("img"));
                menuList.setPrice(rs.getString("price"));
                menuList.setShopName(rs.getString("shopName"));
                menuList.setShopID(rs.getString("shopID"));
                menuList.setShopPhone(rs.getString("shopPhone"));
                menuList.setLikes(rs.getString("likes"));

                menuLists.add(menuList);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        // 将一个集合放到请求域当中
        request.setAttribute("menuList",menuLists);

        // 转发（不要重定向）
        request.getRequestDispatcher("/userMenuList.jsp").forward(request, response);
    }

    private void doUserDetail(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String userName=loginServlet.homeName;
//        String userId=request.getParameter("userID");
        userList userList = new userList();

        Connection conn=null;
        PreparedStatement ps=null;
        ResultSet rs=null;

        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            conn= DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/onlineOrder","root","123456");
            String sql="select id,userName,Pwd,name,phone,sex,address from user where id=?";
            ps=conn.prepareStatement(sql);
            ps.setString(1,loginServlet.ID);
            rs=ps.executeQuery();
            if (rs.next()){
                userList.setUserId(rs.getString("id"));
                userList.setUserName(rs.getString("userName"));
                userList.setPassword(rs.getString("Pwd"));
                userList.setName(rs.getString("name"));
                userList.setPhone(rs.getString("phone"));
                userList.setSex(rs.getString("sex"));
                userList.setAddress(rs.getString("address"));
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        request.setAttribute("userList",userList);

        // 转发（不要重定向）
        request.getRequestDispatcher("/userDetail.jsp").forward(request, response);

    }
}
